'''
Author: duliang thinktanker@163.com
Date: 2024-07-19 10:50:32
LastEditors: duliang thinktanker@163.com
LastEditTime: 2024-07-19 21:34:47
FilePath: \control-net\llj_tcp_server.py
Description: 
'''
import socket


def handle_client(client_socket):
    """
    处理客户端连接，接收数据并回传。
    """
    try:
        # 接收客户端数据
        request = client_socket.recv(1024)

        print(f"Received: {request.decode('utf-8')}")

        # 回复客户端
        client_socket.sendall(str(len(request)).encode('utf-8'))
    except Exception as e:
        print(f"Error occurred: {e}")
    finally:
        # 关闭连接
        client_socket.close()


def main():
    host = '0.0.0.0'  # 监听所有IP地址
    port = 5002  # 选择一个端口

    # 创建socket对象
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # 防止“address already in use”错误
    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    # 绑定IP和端口
    server_socket.bind((host, port))

    # 开始监听，最大连接数为5
    server_socket.listen(5)
    print(f"TCP Server is listening on {host}:{port}")

    while True:
        # 接受一个客户端连接
        client_socket, addr = server_socket.accept()
        print(f"Connected by {addr}")

        # 创建线程来处理每个客户端，这样服务器可以同时处理多个连接
        # 在实际应用中，你可能想使用线程池或其他并发模型以更高效地管理连接
        # 但这里为了简单直接在主线程中处理
        handle_client(client_socket)


if __name__ == "__main__":
    main()
